<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入地块名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            :default-expand-all="false"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="18" v-show="empty"><el-empty description="暂时未添加地块"/></el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24" v-show="showData">
        <el-row>
          <el-col :span="24" v-show="rowShow">
        <el-form :model="params" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" style="float: right">
          <el-form-item label="时间">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
          </el-col>
          <el-col :span="24" v-show="!rowShow">
            <el-form :model="params" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item>
                <el-button type="primary" icon="el-icon-back" size="mini" circle @click="bigChart(null,2)"></el-button>
              </el-form-item>
              <el-form-item style="float: right" >
                <el-button type="warning" plain icon="el-icon-setting" size="mini" @click="dialogVisible=true">映射值设置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <el-row class="flex-container" v-show="rowShow">
          <div>
            <el-col :span="12" class="cardiogram">
              <line-chart :title="this.vmList[0].vmName" :chartId="'6'"  :chartWidth="'100%'" :chartHeight="'100%'" :label="this.label" :labelValue="this.labelValue[0]"  :visualMapData="this.vmList[0].vmData" @lineChartClick="bigChart"/>
            </el-col>
            <el-col :span="12" class="cardiogram">
              <line-chart :title="this.vmList[1].vmName" :chartId="'7'"  :chartWidth="'100%'" :chartHeight="'100%'" :label="this.label" :labelValue="this.labelValue[1]"  :visualMapData="this.vmList[1].vmData" @lineChartClick="bigChart"/>
            </el-col>
          </div>
          <div>
            <el-col :span="12" class="cardiogram">
              <line-chart :title="this.vmList[2].vmName" :chartId="'8'" :chartWidth="'100%'" :chartHeight="'100%'" :label="this.label" :labelValue="this.labelValue[2]" :visualMapData="this.vmList[2].vmData" @lineChartClick="bigChart"/>
            </el-col>
            <el-col :span="12" class="cardiogram">
              <line-chart :title="this.vmList[3].vmName" :chartId="'9'" :chartWidth="'100%'" :chartHeight="'100%'" :label="this.label" :labelValue="this.labelValue[3]" :visualMapData="this.vmList[3].vmData" @lineChartClick="bigChart"/>
            </el-col>
          </div>
        </el-row>

        <el-row v-show="!rowShow" v-if="loadChartFlag">
          <line-chart :title="this.lindChartData.chartTitle" :chartId="this.lindChartData.chartId"  :chartWidth="'1000px'" :chartHeight="'500px'" :label="this.label" :labelValue="this.lindChartData.chartData" :visualMapData="this.vmOption.vmData"  />
        </el-row>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="this.weatherQualityData.rows":height="300" @selection-change="handleSelectionChange" :show-overflow="false">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="空气温度(℃)" align="center"  prop="temp"/>
          <el-table-column label="空气湿度(%)" align="center"  prop="humidity"/>
          <el-table-column label="降水量(mm)" align="center"  prop="precip"/>
          <el-table-column label="大气压强(hPa)" align="center"  prop="pressure"/>
          <el-table-column label="二氧化氮(µg/m³)" align="center"  prop="no2"/>
          <el-table-column label="二氧化硫(µg/m³)" align="center"  prop="so2"/>
          <el-table-column label="一氧化碳(mg/m³)" align="center"  prop="co"/>
          <!--          <el-table-column label="数据量" align="center"  prop="phonenumber"/>-->
          <el-table-column label="时间" align="center" prop="time">
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="this.params.page"
          :page-size="this.params.pageSize"
          :total="1000"
          @current-change="handleCurrentPageChange"
         style="float: right">
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="this.lindChartData.chartTitle+'映射值设置'"
      :visible.sync="dialogVisible"
      :closeOnClickModal="false"
      width="30%"
      v-if="loadChartFlag">
      <el-form ref="form" :model="vmOption" label-width="80px">
        <el-form-item label="偏高范围">
          <el-col :span="5">
            <el-input v-model="vmOption.vmData[2].gt" style="width: 100%"></el-input>
          </el-col>
          <el-col class="line" :span="2"> - </el-col>
          <el-col :span="5">
            <el-input v-model="vmOption.vmData[2].lte" style="width: 100%"></el-input>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="5">
            <el-color-picker v-model="vmOption.vmData[2].color"></el-color-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="正常范围">
          <el-col :span="5">
            <el-input v-model="vmOption.vmData[1].gt" style="width: 100%"></el-input>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="5">
            <el-input v-model="vmOption.vmData[1].lte" style="width: 100%"></el-input>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="5">
            <el-color-picker v-model="vmOption.vmData[1].color"></el-color-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="偏低范围">
          <el-col :span="5">
            <el-input v-model="vmOption.vmData[0].gt" style="width: 100%"></el-input>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="5">
            <el-input v-model="vmOption.vmData[0].lte" style="width: 100%"></el-input>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="5">
            <el-color-picker v-model="vmOption.vmData[0].color"></el-color-picker>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateVmData">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import lineChart from "@/components/LineChart"
import {getWeatherQuality} from "../../../api/agriculture/weather";
import {listLand,} from "@/api/agriculture/land";
import {listVisualMap, updateVisualMap} from "@/api/agriculture/visualMap";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect,lineChart },
  data() {
    return {
      columns:'',
      dialogVisible:false,
      rowShow:true,
      loadChartFlag:false,
      weatherQualityData:[],
      lindChartData:{
        chartTitle:'',
        chartId:'',
        chartData:'',
        chartVm:''
      },
      vmList:[],
      vmOption:{
        vmid:'',
        vmName:'',
        vmData: [
          {
            color: '#FBDB0F',
            gt: 0,
            lte: 4,
          },
          {
            color: '#93CE07',
            gt: 4,
            lte: 6,
          },
          {
            color: '#ED1C24',
            gt: 6,
            lte: 11,
          },
        ],
      },
      // 折线数据
      label:[],
      labelValue:[],
      // 地块列表
      landList:[],
      // 空页面
      empty:false,
      // 显示数据
      showData:true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      params: {
        id:101300806,
        page:1,
        pageSize:10,
        startTime:null,
        endTime:null,
      },
      vmParams:{
        vmId:'',
        vmName:'',
        vmHigh:'',
        vmNormal:'',
        vmLow:'',
        color:'',
      },
     linchartparams: {
        id:101300806,
        page:1,
        pageSize:100000,
        startTime:null,
        endTime:null,
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  async  mounted() {
   await this.fetchWeatherData();
    await this.getVisualMapData()
  },
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    async updateVmData()
    {
      this.vmParams.vmId =this.lindChartData.chartId.replace('id','')
      this.vmParams.vmName=this.lindChartData.chartTitle
      this.vmParams.vmLow = this.vmOption.vmData[0].gt+','+this.vmOption.vmData[0].lte
      this.vmParams.vmNormal = this.vmOption.vmData[1].gt+','+this.vmOption.vmData[1].lte
      this.vmParams.vmHigh = this.vmOption.vmData[2].gt+','+this.vmOption.vmData[2].lte
      this.vmParams.color = this.vmOption.vmData[0].color+','+this.vmOption.vmData[1].color+','+this.vmOption.vmData[2].color
      console.log(this.vmParams)
      try {
        await updateVisualMap(this.vmParams)
        this.openMessage('success', '修改成功！');
        this.dialogVisible=false
      }catch (error){
        console.error('Error occurred while update sellpro:', error);
        this.openMessage('error', '修改失败！');
      }
    },
    bigChart(data,row){
      this.rowShow = !this.rowShow
      if(row !== 1)
      {
        this.loadChartFlag = !this.loadChartFlag
        this.lindChartData.chartTitle=data.title
        this.lindChartData.chartId='id'+data.chartId
        this.lindChartData.chartData=data.labelValue
        this.vmOption.vmData=data.visualMapData
      }
    },
    /** 查询地块列表 */
    async getList() {
      const rows = await listLand();
      this.landList = rows.rows
      const land = this.landList.map(rows => {
        return {
          landName: rows.landName
        };
      });
      const landNames = land.map(land => land.landName).sort(this.sortLandNumber); // 排序地块
      const landData = this. changeToTreeData(landNames)
      this.deptOptions=landData
    },
    // 地块数据转换成树型数据
    changeToTreeData(landData) {
      const treeData = [];
      let count= 1; // 计数设置地块id
      // 循环原始地块数据
      landData.forEach(land => {
        // 分割地块名称
        const [parent, child] = land.split('-');
        // 查找是否已经存在该父节点
        let parentNode = treeData.find(node => node.label === parent);
        // 如果不存在，则创建父节点
        if (!parentNode) {
          parentNode = { id: count++,label: parent, children: [] }; // 为父节点设置 ID
          treeData.push(parentNode);
        }
        // 添加子节点并设置 ID
        parentNode.children.push({ id: count++, label: land });
      });
      return treeData;
    },
    // 对地块进行排序
    sortLandNumber(a, b) {
      // 解析地块名称的第一部分和第二部分
      const [prefixA, x1, y1] = a.match(/(\d+)/g);
      const [prefixB, x2, y2] = b.match(/(\d+)/g);
      // 首先按照地块编号前缀进行排序，然后按照第一部分地块编号进行排序，如果相同，则按照第二部分地块编号进行排序
      if (prefixA !== prefixB) {
        return prefixA.localeCompare(prefixB);
      } else if (parseInt(x1) !== parseInt(x2)) {
        return parseInt(x1) - parseInt(x2);
      } else {
        return parseInt(y1) - parseInt(y2);
      }
    },
    // 警告消息
    openMessage(type,mes) {
      this.$notify({
        title: '提示',
        message: mes,
        offset: 30,
        type: type
      });
    },
     // 分页查询
    handleCurrentPageChange(newPage)
    {
      this.params.page=newPage
      this.fetchWeatherData()
      this.getLinchartData()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.params.page=1
      this.params.startTime=this.changeTime(this.dateRange[0])
      this.params.endTime=this.changeTime(this.dateRange[1])
      this.fetchWeatherData()
      this.getLinchartData()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange=''
      this.params.startTime=null
      this.params.endTime=null
      this.fetchWeatherData()
      this.getLinchartData()
    },
    // 折线图数据
    async getLinchartData()
    {
      const month = new Date()
      const firstDayOfMonth = new Date(month.getFullYear(), month.getMonth()-1, 1)
      const lastDayOfMonth = new Date(month.getFullYear(), month.getMonth() + 1, 1)
      this.linchartparams.startTime=this.changeTime(firstDayOfMonth)
      this.linchartparams.endTime=this.changeTime(lastDayOfMonth)
      const row = await getWeatherQuality(this.linchartparams)
      this.label= row.rows.map(entry => entry.time)
      this.labelValue[0]= row.rows.map(entry => entry.temp)
      this.labelValue[1]= row.rows.map(entry => entry.humidity)
      this.labelValue[2]= row.rows.map(entry => entry.precip)
      this.labelValue[3]= row.rows.map(entry => entry.no2)
    },

    // 获取映射值数据
    async getVisualMapData()
    {
      const row = await listVisualMap()
      this.vmList = [];
      for (let i = 5; i <= 9; i++) {
        const item = row.rows[i];
        const [c1, c2, c3] = item.color.split(',');
        const [h1, h2] = item.vmHigh.split(',');
        const [n1, n2] = item.vmNormal.split(',');
        const [l1, l2] = item.vmLow.split(',');
        this.vmList.push({
          vmId: item.vmId,
          vmName: item.vmName,
          vmData: [
            { color: c1, gt: parseFloat(l1), lte: parseFloat(l2) },
            { color: c2, gt: parseFloat(n1), lte: parseFloat(n2) },
            { color: c3, gt: parseFloat(h1), lte: parseFloat(h2) },
          ],
        });
      }
    },
    // 获取气象数据
    async  fetchWeatherData(){
      this.loading = true;
      const response  =  await  getWeatherQuality(this.params)
      this.weatherQualityData = response;
      this.getLinchartData()
      this.loading = false;
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      const idMapping = {
        1: { showData: true, empty: false },
        2: { showData: false, empty: true },
        3: { showData: false, empty: true },
        4: { showData: false, empty: true },
        5: { showData: false, empty: true },
      };
      const selectedData = idMapping[data.id] || { showData: false, empty: true };
      this.showData = selectedData.showData;
      this.empty = selectedData.empty;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 化时间日期
    changeTime(originalDateString){
      const originalDate = new Date(Date.parse(originalDateString));
      const year = originalDate.getFullYear();
      const month = String(originalDate.getMonth() + 1).padStart(2, '0');
      const day = String(originalDate.getDate()).padStart(2, '0');
      const hours = String(originalDate.getHours()).padStart(2, '0');
      const minutes = String(originalDate.getMinutes()).padStart(2, '0');
      const seconds = String(originalDate.getSeconds()).padStart(2, '0');
      const formattedDateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDateString;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

  },

};
</script>
<style>
.flex-container{
  display: -webkit-flex;
  display: flex;
  justify-content: center; /* 在主轴上居中 */
  align-content: center; /* 在交叉轴上居中 */
  flex-wrap: wrap;
}
.cardiogram{
  height: 30vh;
  width: 35vh;
}
</style>
